import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const addressModule = {
  namespaced: true,
  state: {
    addressInfo: JSON.parse(localStorage.getItem('addressData')) || [],
  },
  getters: {
  },
  mutations: {
    addRess(state, payload) {
      if (state.addressInfo.length === 0) {
        payload.default = true
        payload.checked = true
        state.addressInfo.push(payload)
      } else {
        if (payload.default === true) {
          state.addressInfo.forEach(item => {
            item.default = false
            item.checked = false
          })
        }
        state.addressInfo.push(payload)
      }
    },
    chooseAddress(state, payload) {
      state.addressInfo = state.addressInfo.map(item => {
        const copy = { ...item }
        if (copy.id === payload.id) {
          copy.checked = true
        } else {
          copy.checked = false
        }
        return copy
      })
    },
  },
  actions: {
  },
}

export default addressModule
